package cn.lsc._04_es;

import cn.lsc.util.ESClientUtil;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;

import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

public class Estest {
    @Test
    public void testBatch() throws Exception {
        //得到一个es链接
        TransportClient client = ESClientUtil.getClient();
        BulkRequestBuilder buildr = client.prepareBulk();
        for (int i = 2; i < 100; i++) {
            IndexRequestBuilder builder = client.prepareIndex("pethome", "pet", i+"").setSource(
                    XContentFactory.jsonBuilder()
                            .startObject()
                            .field("id", i - 1)
                            .field("name", "我在源码学Java！" + i)
                            .field("age", i - 1)
                            .field("sex", i % 2)
                            .endObject()
            );
            BulkResponse bulkItemResponses = buildr.add(builder).get();
            System.out.println(bulkItemResponses);
        }
        //关流
        client.close();

    }
    @Test
    public void esTest(){
        //得到一个es链接
        TransportClient client = ESClientUtil.getClient();
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch("pethome");
        //得到bool对象  QueryBuilders是一个方法
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        searchRequestBuilder.setQuery(boolQueryBuilder);

        //往bool对象中设置match条件   QueryBuilders是一个方法
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "我在源码");
        boolQueryBuilder.must(matchQueryBuilder);

        //往bool对象中设置filter条件
        boolQueryBuilder
                .filter(QueryBuilders.termQuery("sex",1))
                        .filter(QueryBuilders.rangeQuery("age").gte(1).lte(12));
        searchRequestBuilder.setQuery(boolQueryBuilder);

        searchRequestBuilder.setSize(2);
        searchRequestBuilder.setFrom(2);
        searchRequestBuilder.addSort("age", SortOrder.DESC);


        SearchHit[] hits = searchRequestBuilder.get().getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
        client.close();
    }
}
